import { createI18n } from 'vue-i18n';
import messages from '@/locales/lang/en';

export const supportLanguages: string[] = ['en', 'zh-CN', 'zh-TW'];

const i18n: any = createI18n({
  legacy: false,
  globalInjection: true,
  locale: 'en', // set locale
  fallbackLocale: 'en',
  availableLocales: supportLanguages,
  messages
});
const loadedLanguages = ['en']; // our default language that is preloaded

function setI18nLanguage(lang: string): string {
  i18n.locale = lang;
  // axios.defaults.headers.common['Accept-Language'] = lang;
  window.document.querySelector('html')?.setAttribute('lang', lang);
  return lang;
}

export function loadLanguageAsync(lang: string) {
  // If the same language
  if (i18n.locale === lang) {
    return Promise.resolve(setI18nLanguage(lang));
  }

  // If the language was already loaded
  if (loadedLanguages.includes(lang)) {
    return Promise.resolve(setI18nLanguage(lang));
  }
  const modules = import.meta.glob('@/locales/lang/*.ts', { eager: false });
  // If the language hasn't been loaded yet
  return modules[`@/locales/lang/${lang}.ts`]().then((messages: any) => {
    i18n.setLocaleMessage(lang, messages.default);
    loadedLanguages.push(lang);
    return setI18nLanguage(lang);
  });
}

export default i18n;
